package com.gxuwz.stats.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.entity.ResearchPlatform;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.ResearchPlatformService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userResearchPlatform")
public class ResearchPlatformUserController {

    @Autowired
    private ResearchPlatformService researchPlatformService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserRePlatformList")
    public ResponseEntity<Map<String, Object>> getUserRePlatformList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            // 提取 Token
            String token = authorization.replace("Bearer ", "");

// 解析 Token 获取当前用户ID（假设使用 JWT）
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            String userId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<ResearchPlatform> page = new Page<>(currentPage, pageSize);
            QueryWrapper<ResearchPlatform> queryWrapper = new QueryWrapper<>();


// 强制添加当前用户ID条件
            queryWrapper.eq("user_id", userId);

            // 模糊查询条件 - 科研基地名称
            if (params.containsKey("platformName") && params.get("platformName") != null && !params.get("platformName").isEmpty()) {
                queryWrapper.like("platform_name", params.get("platformName"));
            }

            // 模糊查询条件 - 类别
            if (params.containsKey("platformType") && params.get("platformType") != null && !params.get("platformType").isEmpty()) {
                queryWrapper.like("platform_type", params.get("platformType"));
            }

            if (params.containsKey("platformCategory") && params.get("platformCategory") != null && !params.get("platformCategory").isEmpty()) {
                queryWrapper.like("platform_category", params.get("platformCategory"));
            }

            // 模糊查询条件 - 获得时间
            if (params.containsKey("platformYear") && params.get("platformYear") != null && !params.get("platformYear").isEmpty()) {
                queryWrapper.apply("YEAR(platform_year) = {0}", params.get("platformYear"));
            }

            // 精确查询条件 - 项目提交状态
            if (params.containsKey("platformStatus") && params.get("platformStatus") != null && !params.get("platformStatus").isEmpty()) {
                queryWrapper.eq("platform_status", params.get("platformStatus"));
            }

            // 精确查询条件 - 项目审核状态
            if (params.containsKey("platformReviewStatus") && params.get("platformReviewStatus") != null && !params.get("platformReviewStatus").isEmpty()) {
                queryWrapper.eq("platform_review_status", params.get("platformReviewStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<ResearchPlatform> resultPage = researchPlatformService.getRPListWithUserInfo(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增决策咨询数据
     */
    @PostMapping("/addRePlatform")
    public ResponseEntity<Map<String, Object>> saveResearchPlatform(@RequestBody ResearchPlatform researchPlatform) {
//        System.out.println("前端数据：" + researchPlatform);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();

        // 1. 验证 username 是否存在
        String username = researchPlatform.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        researchPlatform.setUserId(userId);

        // 1. 自动计算分值
        int baseScore = researchPlatformService.getScoreByType(researchPlatform.getPlatformCategory());
        researchPlatform.setPlatformScore(baseScore);

        // 2. 计算总分值
        double totalScore = researchPlatformService.calculateTotalScore(researchPlatform);
        researchPlatform.setPlatformTotalScore(totalScore);

        researchPlatform.setPlatformStatus("未提交");
        researchPlatform.setPlatformReviewStatus("未审核");



        try {
            // 保存到数据库
            researchPlatformService.save(researchPlatform);
            String year = null;
            if (researchPlatform.getPlatformYear() != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(researchPlatform.getPlatformYear());
            }
            if (year != null) {
                researchPlatformService.updateTotalWorkPlatformScore(userId, year);
            }


            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/updateRePlatform")
    public ResponseEntity<Map<String, Object>> updateResearchPlatform(
            @RequestBody ResearchPlatform researchPlatform
    ) {
//        System.out.println("343242="+researchPlatform);
        // 1. 自动计算分值
        int baseScore = researchPlatformService.getScoreByType(researchPlatform.getPlatformCategory());
        researchPlatform.setPlatformScore(baseScore);

        // 2. 计算总分值
        double totalScore = researchPlatformService.calculateTotalScore(researchPlatform);
        researchPlatform.setPlatformTotalScore(totalScore);



        researchPlatformService.updateById(researchPlatform);
        String year = null;
        if (researchPlatform.getPlatformYear() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            year = sdf.format(researchPlatform.getPlatformYear());
        }
        if (year != null) {
            researchPlatformService.updateTotalWorkPlatformScore(researchPlatform.getUserId(), year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     */
    @DeleteMapping("/delUserRePlatform")
    public ResponseEntity<Map<String, Object>> deleteUserRePlatform(@RequestBody List<Long> researchPlatformIds) {
        // 1. 查出所有要删的数据
        List<ResearchPlatform> toDelete = researchPlatformService.listByIds(researchPlatformIds);

// 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (ResearchPlatform rp : toDelete) {
            if (rp.getUserId() != null && rp.getPlatformYear() != null && !rp.getPlatformYear().isEmpty()) {
                String year;
                try {
                    year = new SimpleDateFormat("yyyy").format(new SimpleDateFormat("yyyy-MM").parse(rp.getPlatformYear()));
                } catch (Exception e) {
                    year = rp.getPlatformYear().substring(0, 4);
                }
                userYearSet.add(rp.getUserId() + "#" + year);
            }
        }

// 3. 删除
        researchPlatformService.removeByIds(researchPlatformIds);

// 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            researchPlatformService.updateTotalWorkPlatformScore(userId, year);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 用户提交重要平台
     */
    @PostMapping("/submitRePlatform")
    public ResponseEntity<Map<String, Object>> submitRePlatform(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long platformId = Long.valueOf(params.get("platformId").toString());
        ResearchPlatform platform = researchPlatformService.getById(platformId);
        if (platform == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        platform.setPlatformStatus("已提交");
        platform.setPlatformReviewStatus("未审核");
        platform.setPlatformReviewTime(null);
        platform.setPlatformSubmissionTime(LocalDateTime.now());
        researchPlatformService.updateById(platform);
        response.put("code", 200);
        response.put("msg", "提交成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 用户撤回重要平台
     */
    @PostMapping("/revokeRePlatform")
    public ResponseEntity<Map<String, Object>> revokeRePlatform(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long platformId = Long.valueOf(params.get("platformId").toString());
        ResearchPlatform platform = researchPlatformService.getById(platformId);
        if (platform == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.ok(response);
        }
        // 只有审核通过/审核不通过不能撤回，其余都能撤回
        if ("审核通过".equals(platform.getPlatformReviewStatus()) || "审核不通过".equals(platform.getPlatformReviewStatus())) {
            response.put("code", 400);
            response.put("msg", "已审核，不可撤回");
            return ResponseEntity.ok(response);
        }
        platform.setPlatformStatus("未提交");
        platform.setPlatformSubmissionTime(null);
        platform.setPlatformReviewTime(null);
        researchPlatformService.updateById(platform);
        response.put("code", 200);
        response.put("msg", "撤回成功");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/export")
    public void exportResearchPlatform(
            @RequestParam(value = "year", required = false) String year,
            @RequestHeader("Authorization") String authorization,
            HttpServletResponse response) throws Exception {
        // 1. 解析token获取userId
        String token = authorization.replace("Bearer ", "");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String userId = jwtTokenUtil.getUserIdFromToken(token);

        // 2. 查找用户名
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId));
        String username = user != null ? user.getUsername() : "未知用户";

        // 3. 查询 ResearchPlatform（可按年份筛选）
        QueryWrapper<ResearchPlatform> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 只查当前用户
        if (year != null && !year.isEmpty()) {
            queryWrapper.like("platform_year", year.substring(0, 4)); // 替换为你的年份字段
        }

        // 只导出审核通过的数据
//        queryWrapper.eq("platform_review_status", "审核通过");

        List<ResearchPlatform> list = researchPlatformService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (ResearchPlatform rp : list) {
            rp.setUsername(userIdNameMap.getOrDefault(rp.getUserId(), ""));
        }

        // 5. 给每条数据加序号（如有 rowNum 字段）
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 如果有 rowNum 字段
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "重要平台-" + username + "-" + now + ".xlsx";

        // 7. 导出
        ExcelExportUtil.export(response, list, ResearchPlatform.class, "重要平台", fileName);
    }

}
